package providev.learn.imagina.tema3_1;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class Preferences extends Activity{
	CheckBox mostrarImagen;
    EditText textName;
    public static final String PREF_MOSTRAR_IMAGEN = "PREF_MOSTRAR_IMAGEN";
    public static final String PREF_NOMBRE = "PREF_NOMBRE";

    SharedPreferences prefs;
    @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.preferences);
            mostrarImagen = (CheckBox)findViewById(R.id.checkbox_imagen);
            textName = (EditText)findViewById(R.id.textNombre);Context context = getApplicationContext();
            prefs = PreferenceManager.getDefaultSharedPreferences(context);
            updateUIFromPreferences();
            
            Button okButton = (Button) findViewById(R.id.okButton);
            okButton.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view) {
                            savePreferences();
                            Preferences.this.setResult(RESULT_OK);
                            finish();
                    }
            });

            Button cancelButton = (Button) findViewById(R.id.cancelButton);
            cancelButton.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view) {
                            Preferences.this.setResult(RESULT_CANCELED);
                            finish();
                    }
            });
    }

    private void updateUIFromPreferences() {
            boolean mostrarImagenChecked = prefs.getBoolean(PREF_MOSTRAR_IMAGEN, false);
            String nombre = prefs.getString(PREF_NOMBRE, "");
            mostrarImagen.setChecked(mostrarImagenChecked);
            textName.setText(nombre);
    }
    
    private void savePreferences() {
        boolean mostrarImagenChecked = mostrarImagen.isChecked();
        Editor editor = prefs.edit();
        editor.putBoolean(PREF_MOSTRAR_IMAGEN, mostrarImagenChecked);
        editor.putString(PREF_NOMBRE, textName.getText().toString());
        editor.commit();
}
    
}
